import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

const store = new Vuex.Store({
  state: {
    list: JSON.parse(window.localStorage.getItem('todos')) || [],
    selectedStatus: window.location.hash
  },
  mutations: {
    changeFlag (state, id) {
      var obj = state.list.find(item => item.id === id)
      obj.flag = !obj.flag
    },
    remove (state, id) {
      var index = state.list.findIndex(item => item.id === id)
      state.list.splice(index, 1)
    },
    save (state, { id, newVal }) {
      var obj = state.list.find(item => item.id === id)
      obj.name = newVal
    },
    add (state, val) {
      var id
      if (state.list.length === 0) {
        id = 1
      } else {
        id = state.list[state.list.length - 1].id + 1
      }
      var obj = {
        id,
        name: val,
        flag: false
      }
      state.list.push(obj)
    },
    removeAll (state) {
      state.list = state.list.filter(item => item.flag === false)
    },
    changeSelectedStatus (state) {
      state.selectedStatus = window.location.hash
    },
    changeAll (state, flag) {
      state.list = state.list.map(item => {
        item.flag = flag
        return item
      })
    }
  },
  actions: {
  },
  getters: {
    count (state) {
      return state.list.filter(item => item.flag === false).length
    },
    myList (state) {
      if (state.selectedStatus === '#/active') {
        return state.list.filter(item => item.flag === false)
      } else if (state.selectedStatus === '#/completed') {
        return state.list.filter(item => item.flag === true)
      } else {
        return state.list
      }
    },
    all (state) {
      return state.list.length === state.list.filter(item => item.flag === true).length
    }
  },
  modules: {
  }
})

window.onhashchange = function () {
  store.commit('changeSelectedStatus')
}

export default store
